package com.colorlight.cloud.shell;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 */
public class ProtoCompiler {
    /**
     * 打包指令为 可执行语句
     *
     * @param basePath 源文件目录
     * @param target   输出文件目录目录
     **/
    public static void builderProtoCompiler(String basePath, String target) throws IOException {
        // 获取目标目录对象
        Path directoryPath = Paths.get(basePath);
        List<String> allProtoFileNames = Files.walk(directoryPath)
                .filter(path -> path.getFileName().toString().endsWith(".proto"))
                .map(Path::toString).collect(Collectors.toList());
        String command = builderProtoCompiler(basePath, target, allProtoFileNames);
        System.out.println(command);
        cmdShell(command);
    }

    /**
     * 打包指令为 可执行语句
     *
     * @param basePath          源文件目录
     * @param target            目标目录
     * @param allProtoFileNames proto文件集合
     * @return 可执行语句
     **/
    public static String builderProtoCompiler(String basePath, String target, List<String> allProtoFileNames) {
        String path = String.join(" ", allProtoFileNames);
        return String.format("protoc -I=%s --java_out=%s %s", basePath, target, path);
    }

    /**
     * 执行指令
     *
     * @param command 指令串
     **/
    public static void cmdShell(String command) {

        try {
            // 执行命令
            Process process = new ProcessBuilder("cmd", "/c", command).start();

            // 等待命令执行完毕
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Java files copied successfully.");
            } else {
                System.err.println("Error compiling Protocol Buffers files. Exit code: " + exitCode);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

